package com.jy.oms.framework.asyn.job;

import cn.hutool.core.thread.ThreadUtil;
import com.jy.oms.framework.asyn.task.core.ExecutorConfig;
import com.jy.oms.framework.asyn.task.core.ExecutorContext;
import com.jy.oms.framework.asyn.task.core.WorkerServerThreadManager;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 单机版任务切面
 * <p>
 * 启动配置参考
 *
 * @author liuquan
 * @see com.jy.oms.framework.asyn.task.core.ExecutorStarterListener
 */
@Component
@Aspect
public class StandaloneJobAspectHandler {
    private static Logger logger = LoggerFactory.getLogger(StandaloneJobAspectHandler.class);

    @Around("this(com.jy.oms.framework.asyn.job.IStandaloneJob)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class target = joinPoint.getTarget().getClass();
        String methodName = signature.getMethod().getName();
        if (!StringUtils.equalsIgnoreCase(methodName, IStandaloneJob.JOB_METHOD)) {
            return joinPoint.proceed();
        }

        boolean ableRunJob = this.judgeAbleRunJob(target);
        if (!ableRunJob) {
            if (AbstractLoopStandaloneJob.class.isAssignableFrom(target)) {
                ThreadUtil.sleep(1, TimeUnit.MINUTES);
            }

            return null;
        }

        return joinPoint.proceed();
    }

    private boolean judgeAbleRunJob(Class target) {
        ExecutorConfig executorConfig = ExecutorContext.getExecutorConfig();
        if(executorConfig == null){
            return false;
        }

        StandaloneJobConfig standaloneJobConfig = executorConfig.getStandaloneJobConfig();
        if (!standaloneJobConfig.isEnableJob()) {
            logger.info("跳过JOB, {}", target);
            return false;
        }

        if (CollectionUtils.isNotEmpty(standaloneJobConfig.getEnableSpecJobs())) {
            if (!standaloneJobConfig.getEnableSpecJobs().contains(target)) {
                logger.info("跳过JOB, {}", target);
                return false;
            }
        }

        if (!WorkerServerThreadManager.getInstance().isWorkerServer()) {
            logger.info("不是WorkerServer, 跳过JOB, {}", target);
            return false;
        }

        return true;
    }

}
